/*
 *
 * CardFileController.m
 *
 *	You may freely copy, distribute and reuse the code in this example.
 *	NeXT disclaims any warranty of any kind, expressed or implied, as to
 *	its fitness for any particular use.
 *
 */

#import "CardFileController.h"

@implementation CardFileController

- init
{
	[super init];
	customerList = [[List alloc] init];
	return self;
}

- awakeFromNib
{
	[self addCustomer:self];
	[[nameField window] makeKeyAndOrderFront:self];
	return self;
}

- free
{
	[customerList freeObjects];
	[customerList free];
	return [super free];
}

- addCustomer:sender
{
	currentCustomer = [[Customer alloc] init];
	[customerList addObject:currentCustomer];
	[self updateInspector];
    return self;
}

- deleteCustomer:sender
{
	// XXX - probably should confirm this operation with the User
	if (!currentCustomer) return self; // XXX - better to disable the menu item
	
	[customerList removeObject:currentCustomer];
	[currentCustomer free];
	[self firstCustomer];
    return self;
}

- nextCustomer:sender
{
	id  nextCustomer;
	int customerIndex = [customerList indexOf:currentCustomer];
	
	if (customerIndex == NX_NOT_IN_LIST){
		NXBeep();
		return self;
	}
	nextCustomer = [customerList objectAt:(customerIndex + 1)];
	if (!nextCustomer) {
		NXBeep();
		return self;
	}
	currentCustomer = nextCustomer;
	[self updateInspector];
    return self;
}

- prevCustomer:sender
{
	id  prevCustomer;
	int customerIndex = [customerList indexOf:currentCustomer];
	
	if (customerIndex == NX_NOT_IN_LIST){
		NXBeep();
		return self;
	}
	if (customerIndex == 0) {
		NXBeep();
		return self;
	}
	
	prevCustomer = [customerList objectAt:(customerIndex - 1)];
	if (!prevCustomer) 
		return self;	// should also alert user that this is last
	currentCustomer = prevCustomer;
	[self updateInspector];
    return self;
}

- firstCustomer
{
	currentCustomer = [customerList objectAt:0];
	if (!currentCustomer) {
		[self clearInspector];
		return self;
	}
	[self updateInspector];
	return self;
}

- nameChanged:sender
{
	[currentCustomer setCustomerName:[sender stringValue]];
    return self;
}

- uidChanged:sender
{
	[currentCustomer setCustomerUid:[sender intValue]];
    return self;
}

- updateInspector
{
	if (!currentCustomer) {
		[self clearInspector];
		return self;
	}
	[nameField setStringValue:[currentCustomer customerName]];
	[uidField setIntValue:[currentCustomer customerUid]];
	[nameField selectText:self];
	return self;
}

- clearInspector
{
	[nameField setStringValue: NULL];
	[uidField setStringValue: NULL];
	
	[nameField selectText:self];
	return self;
}


@end
